package com.dongdongshop.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
@RefreshScope
@Order(-1)
public class LoginFilter implements GlobalFilter {

    @Value("#{'${exclude.url}'.empty?null:'${exclude.url}'.split(',')}")
    private Set<String> urls;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();


        String path = exchange.getRequest().getURI().getPath();
        for (String url : urls) {
            if (antPathMatcher.match(url, path)) {
                return chain.filter(exchange);
            }
        }

        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (token == null) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            //设置响应内容
            Result<Object> result = Result.error(ResultEnum.UNAUTHORIZED);
            //不输出为null的字段
            byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue);
            DataBuffer wrap = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(wrap));
        }
        JwtUtil jwtUtil = new JwtUtil();
        try {
            Claims jwt = jwtUtil.parseJwt(token);
            ServerHttpRequest request1 = exchange.getRequest().mutate()
                    .header("userId", jwt.getId())
                    .build();

            return chain.filter(exchange.mutate().request(request1).build());

        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.OK);
            //设置响应内容
            Result<Object> result = Result.error(ResultEnum.UNAUTHORIZED);
            //不输出为null的字段
            byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue);
            DataBuffer wrap = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(wrap));
        }
    }
}
